<template>
  <div class="login-container">
    <img src="../../assets/img/alogin-back.jpg" alt="" class="login-back" />
    <el-form
      :label-position="right"
      label-width="auto"
      :model="formData"
      :size="big"
      :mode="ruleModel"
      :rules="rules"
      ref="ruleForm"
    >
      <el-form-item prop="username">
        <el-input
          v-model="formData.username"
          :prefix-icon="User"
          placeholder="手机号/邮箱"
          maxlength="20"
          clearable
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="formData.password"
          :prefix-icon="Lock"
          type="password"
          clearable
          placeholder="密码"
          maxlength="20"
          show-password
        />
      </el-form-item>
      <el-form-item prop="code">
        <el-row style="width: 100%" :gutter="20" justify="space-between">
          <el-col :span="16">
            <el-input
              v-model="formData.code"
              :prefix-icon="PieChart"
              clearable
              maxlength="4"
              placeholder="验证码"
            />
          </el-col>
          <el-col :span="8">
            <el-image
              :src="captcha.img"
              style="width: 100%"
              @click="getCaptcha"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="memorize" label="记住密码" size="large" />
      </el-form-item>
      <el-form-item>
        <span class="fcolor-1">
          没有账号？
          <el-button @click="toRegister" type="text"> 去注册 </el-button></span
        >
        <el-button style="width: 100%" type="primary" @click="onLogin">
          登录
        </el-button>
        <div style="text-align: center">
          <el-button type="text" @click="openFind">忘记密码</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
  <find-pass ref="findRef" @code="onGetCode" @submit="onSubmit"></find-pass>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import request from "@/assets/js/request";
import { ElMessage } from "element-plus";
import findPass from "@/components/other/find-pass.vue";
import { useRouter } from "vue-router";

const ruleForm = ref();
const rules = ref({
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const findRef = ref();

const openFind = () => {
  findRef.value.open();
};

const router = useRouter();
const memorize = ref(false);

const ruleModel = ref({
  username: "",
  password: "",
  code: "",
});

const formData = ref({
  username: "",
  password: "",
  code: "",
  uuid: "",
  type: 1,
});

const captcha = ref({
  uuid: "",
  img: "",
});

const onGetCode = (email) => {
  if (email === "" || email === null) {
    ElMessage.warning("抱歉，邮箱不能为空~");
    return;
  }
  request
    .get(`/mail/captcha?mail=${email}`)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("发送成功，注意查收");
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

// 找回密码
const onSubmit = (data) => {
  console.log(data);
  request
    .post("/client/user/find-pass", data)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("修改成功");
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

const onLogin = () => {
  ruleForm.value.validate((valid) => {
    if (valid) {
      formData.value.uuid = captcha.value.uuid;
      if (memorize.value) {
        localStorage.setItem(
          "USER_PASS",
          JSON.stringify({
            username: formData.value.username,
            password: formData.value.password,
          })
        );
      }
      request
        .post("/common/login", formData.value)
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success("登录成功");
            localStorage.setItem(
              "account",
              JSON.stringify({
                username: formData.value.username,
              })
            );
            localStorage.setItem("token", res.data.token);
            localStorage.setItem("user", JSON.stringify(res.data.user));
            router.push("/");
          }
        })
        .catch((err) => {
          ElMessage.error(err.message);
        });
    }
  });
};

const toRegister = () => {
  router.push("/register");
};

// 获取验证码
const getCaptcha = () => {
  request
    .get("/common/captcha")
    .then((res) => {
      if (res.code == 200) {
        captcha.value.uuid = res.data.uuid;
        captcha.value.img = res.data.base64Img;
      } else {
        ElMessage({
          message: res.msg,
          grouping: true,
          type: "warning",
        });
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

onMounted(() => {
  let acount = localStorage.getItem("USER_PASS");
  if (acount !== null) {
    acount = JSON.parse(acount);
    formData.value.username = acount.username;
    formData.value.password = acount.password;
  }
  getCaptcha();
});
</script>

<style scoped></style>
